/**
 * Author: Ravi Tamada
 * URL: www.androidhive.info
 * twitter: http://twitter.com/ravitamada
 * */
package com.whereistheparty;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Ref;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public class UserFunctions {
	
	private JSONParser jsonParser;   
	  
	private static String loginURL = 	"http://web.yapayzeka.com/www/muziksev/android_login_api/";
	private static String registerURL = "http://web.yapayzeka.com/www/muziksev/android_login_api/";
	private static String partyURL = 	"http://web.yapayzeka.com/www/muziksev/android_login_api/";
	private static String locationURL = "http://web.yapayzeka.com/www/muziksev/android_login_api/";
	private static String getpartyURL = "http://web.yapayzeka.com/www/muziksev/android_login_api/";	
	private static String addfriendURL = "http://web.yapayzeka.com/www/muziksev/android_login_api/"; 
	private static String attendpartyURL = "http://web.yapayzeka.com/www/muziksev/android_login_api/attendinsertparty.php";
	private static String removeFriendURL = "http://web.yapayzeka.com/www/muziksev/android_login_api/removefriend.php";

	
	
	private static String login_tag = 		"login";
	private static String register_tag = 	"register";
	private static String party_tag = 		"rte";
	private static String partyupdate_tag = "partyupdate";
	private static String partyremove_tag = "partyremove";
	private static String location_tag = 	"registerlocation";
	private static String getparty_tag = 	"getparty";
	private static String addfriend_tag = 	"addfriend";
	

	// constructor
	public UserFunctions(){
		jsonParser = new JSONParser();
	}
	/**
	 * function make Login Request
	 * @param email
	 * @param password
	 * */
	public JSONObject loginUser(String email, String password)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", login_tag));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("password", password));
		JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
		// return json
		// Log.e("JSON", json.toString());
		return json;
	}
	
	public JSONObject GetPartyDetails(String partyName, String description,
									  String type, String startTime,
									  String finishTime, String location,String partydate)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", getparty_tag));
		params.add(new BasicNameValuePair("partyName", partyName));
		params.add(new BasicNameValuePair("partyDescription", description));
		params.add(new BasicNameValuePair("partyType", type));
		params.add(new BasicNameValuePair("partyStartTime", startTime));
		params.add(new BasicNameValuePair("partyFinishTime", finishTime));
		params.add(new BasicNameValuePair("partyLocation", location));
		params.add(new BasicNameValuePair("partydate", partydate));
		JSONObject json = jsonParser.getJSONFromUrl(getpartyURL, params);
		// return json
		// Log.e("JSON", json.toString());
		return json;
	}
	
	/**
	 * function make Login Request
	 * @param name
	 * @param email
	 * @param password
	 * */
	public JSONObject registerUser(String name, String email, String password){
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", register_tag));
		params.add(new BasicNameValuePair("name", name));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("password", password));
		
		// getting JSON Object
		JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
		// return json
		return json;
	}
	public JSONObject AddFriend(String email,String id)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", addfriend_tag));
		params.add(new BasicNameValuePair("id", id));
		params.add(new BasicNameValuePair("email", email));

		// getting JSON Object
		JSONObject json = jsonParser.getJSONFromUrl(addfriendURL, params);
		// return json
		return json;
	}
	public JSONObject registerParty(String partyName, String description, String type, String startTime, String finishTime, String latitude,String longitude,String email,String partydate,String partyfinishdate)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", party_tag));
		params.add(new BasicNameValuePair("partyName", partyName));
		params.add(new BasicNameValuePair("partyDescription", description));
		params.add(new BasicNameValuePair("partyType", type));
		params.add(new BasicNameValuePair("partyStartTime", startTime));
		params.add(new BasicNameValuePair("partyFinishTime", finishTime));
		params.add(new BasicNameValuePair("partyLatitude", latitude));
		params.add(new BasicNameValuePair("partyLongitude", longitude));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("partydate", partydate));
		params.add(new BasicNameValuePair("partyfinishdate", partyfinishdate));
		
		
		// getting JSON Object
		JSONObject json = jsonParser.getJSONFromUrl(partyURL, params);
		// return json
		return json;
	}
	public JSONObject updateParty(String id, String partyName, String description, String type, String startTime, String finishTime, String latitude,String longitude,String email,String partydate,String partyfinishdate)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", partyupdate_tag));
		params.add(new BasicNameValuePair("id", id));
		params.add(new BasicNameValuePair("partyName", partyName));
		params.add(new BasicNameValuePair("partyDescription", description));
		params.add(new BasicNameValuePair("partyType", type));
		params.add(new BasicNameValuePair("partyStartTime", startTime));
		params.add(new BasicNameValuePair("partyFinishTime", finishTime));
		params.add(new BasicNameValuePair("partyLatitude", latitude));
		params.add(new BasicNameValuePair("partyLongitude", longitude));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("partydate", partydate));
		params.add(new BasicNameValuePair("partyfinishdate", partyfinishdate));

		// getting JSON Object
		JSONObject json = jsonParser.getJSONFromUrl(partyURL, params);
		// return json
		return json;
	}
	public JSONObject removeParty(String id)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", partyremove_tag));
		params.add(new BasicNameValuePair("id", id));

		JSONObject json = jsonParser.getJSONFromUrl(partyURL, params);
		// return json
		return json;
	}
	public JSONObject removeFriend(String id,String email)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", id));
		params.add(new BasicNameValuePair("email", email));
		
		JSONObject json = jsonParser.getJSONFromUrl(removeFriendURL, params);
		// return json
		return json;
	}
	public JSONObject AttendToParty(String partyName)
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("partyName", partyName));
		params.add(new BasicNameValuePair("email", WhereisthepartyActivity.email));
	
		JSONObject json = jsonParser.getJSONFromUrl(attendpartyURL, params);
		// return json
		return json;
	}
	public List<String> getAttendList(String partyName)
	{
		List<String> list = new ArrayList<String>();
		List<String> listpartyname = new ArrayList<String>();
			String result = "";
			InputStream is = null;
		
			try
			{
				is = getAttendListAsString(partyName);
			} 
			catch (Exception e11) 
			{
				Log.e("log_tag", "Error in http connection" + e11.toString());                                                       
			}
		
			// convert response to string
		
			try 
			{
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
		
				while ((line = reader.readLine()) != null) 
				{
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
		
			} 
			catch (Exception e1) 
			{
				Log.e("log_tag", "Error converting result" + e1.toString());
			}
		
			// parse json data
			try 
			{
				JSONArray jArray = new JSONArray(result);
				 
				for (int i = 0; i < jArray.length(); i++) 
				{
					JSONObject json_data = jArray.getJSONObject(i);		                             
					list.add(json_data.getString("email"));						
					listpartyname.add(json_data.getString("partyName"));					
				}		
			}
			 
			catch (JSONException e) 
			{
				Log.e("log_tag", "Error parsing data" + e.toString());
			}
			AttendToParty2 par = new AttendToParty2();
			par.partyNameList = listpartyname;
			return list;
	 
	}
	private InputStream getAttendListAsString(String partyName) 
	{
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://web.yapayzeka.com/www/muziksev/android_login_api/getattendlist.php");
		  	
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("partyName", partyName));

		try
		{
	
			httppost.setEntity(new UrlEncodedFormEntity(params));
	
			HttpResponse response = httpclient.execute(httppost);
		
		    ResponseHandler<String> responseHandler = new BasicResponseHandler();
	        String res = httpclient.execute(httppost, responseHandler);
	        System.out.println("Response : " + res);
	        			
			HttpEntity entity = response.getEntity();
			
			InputStream is = entity.getContent();
			
			return is;
		}
		catch (Exception e)
		{
			return null;
		}
	}
	public JSONObject registerlocation(String email, String longitude, String latitude){
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", location_tag));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("lastlocationlongitude", longitude));
		params.add(new BasicNameValuePair("lastlocationlatitude", latitude));
		
		// getting JSON Object
		JSONObject json = jsonParser.getJSONFromUrl(locationURL, params);
		
		return json;
	}
	/**
	 * Function get Login status
	 * */
	public boolean isUserLoggedIn(Context context)
	{
		DatabaseHandler db = new DatabaseHandler(context);
		int count = db.getRowCount();
		if(count > 0){
			// user logged in
			return true;
		}
		return false;
	}
	
	/**
	 * Function to logout user
	 * Reset Database
	 * */
	public boolean logoutUser(Context context)
	{
		DatabaseHandler db = new DatabaseHandler(context);
		db.resetTables();
		return true;
	}
	
}
